<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写Promise.all</title>
</head>

<body>
    <script>
        //Promise 的状态有三个，pending, resolve, reject
        //它只能从pending 到 resolve 或者 reject，不能逆向
        Promise.MyAll = function (promises) {
            let arr = [] // 存放所有promise的resolve结果
            let count = 0 // 计数器, 记录成功的promise数量

            return new Promise((resolve, reject) => {
                // resolve -> all promise 所有都是resolve才能调用
                //如果promise[i] 不是promise怎么办？Promise.resolve()
                promises.forEach((item, i) => {
                    // 如果item不是promise,则变成promise
                    Promise.resolve(item).then(res => {
                        arr[i] = res
                        count++
                        if (count === promises.length) resolve(arr)
                    }).catch(reject)
                })
            })
        }
    </script>
</body>

</html>